<template>
    <canvas ref="canvasRef" @click="refreshCode" :style="{ cursor: 'pointer' }"></canvas>
</template>

<script setup>
import { ref, onMounted, defineEmits} from 'vue';
// 通过 codeGenerated 自定义事件将生成的验证码传递出去
const emits = defineEmits(['codeGenerated']);
const canvasRef = ref(null);
const codeLength = 4;
const codeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let code = '';

const generateCode = () => {
    code = '';
    for (let i = 0; i < codeLength; i++) {
        const randomIndex = Math.floor(Math.random() * codeChars.length);
        code += codeChars.charAt(randomIndex);
    }
    const newCode = code.toLowerCase()
    // 在 generateCode 方法里触发该事件并传递生成的验证码。
    emits('codeGenerated', newCode);
    return newCode;
};

const drawCode = () => {
    const canvas = canvasRef.value;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制背景
    ctx.fillStyle = '#f5f5f5';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制验证码
    ctx.font = '60px Arial';
    ctx.fillStyle = '#333';
    for (let i = 0; i < code.length; i++) {
        const x = (canvas.width / (code.length + 1)) * (i + 1);
        const y = canvas.height / 2 + 10;
        ctx.fillText(code[i], x, y);
    }

    // 绘制干扰线
    for (let i = 0; i < 5; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.strokeStyle = '#ccc';
        ctx.stroke();
    }
};

const refreshCode = () => {
    generateCode();
    drawCode();
};

onMounted(() => {
    generateCode();
    drawCode();
});
</script>

<style scoped>
canvas {
    /*border: 1px solid #ccc;*/
    padding-left: 3px;
    height: 32px;
    width: 100%;

}
</style>